<?php

namespace app\index\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Session;
use think\Validate;
use tree\Tree;

class Plan extends Controller
{
    /**
     * 用户注册3天未打卡修改用户的打卡状态为不正常，用户将无法打卡
     * */
    public function checkClockStatus()
    {
        $data = [
            'clock_status' => 0,
            'end_clock_date' => null,
            'update_time' => time()
        ];
        Db::name('user')->where(['end_clock_date' => ['<=', date('Y-m-d')], 'clock_status' => 1, 'user_type' => 1])->update($data);
    }

    /**
     * 每日指定时间提醒用户打卡
     * */
    public function clockRemind()
    {
        // 可以打卡的用户id集合（暂未生成打卡记录）
        $ids_arr = Db::name('user')->where(['clock_status' => 1, 'user_type' => 1])->column('id');
        $new_ids_arr = [];
        if($ids_arr){
            foreach($ids_arr as &$v){
                $new_ids_arr[] = [
                    'user_id' => $v,
                    'day' => 1
                ];
            }
        }

        // 当前未打卡的用户集合（已生成打卡记录）
        $user_ids_arr = Db::name('user_clock')->field('user_id,day')->where(['ck_date' => date('Y-m-d'), 'status' => 0])->select();

        $arr = array_merge($new_ids_arr, $user_ids_arr ?: []);

        if($arr){
            $msg_data = [];
            foreach($arr as $v){
                $msg_data[] = insertMsgData($v['user_id'], 'clock_remind', $v['day']);

                // 未打卡微信通知
                $data = [
                    "thing1" => [
                        "value" => "您好，您今日还未打卡，麻烦打个卡吧！"
                    ],
                    "time2" => [
                        "value" => date('Y-m-d') . ' ' . C('CLOCK_END_TIME')
                    ],
                    "time3" => [
                        "value" => date('Y年m月d日')
                    ],
                    "phrase8" => [
                        "value" => '未打卡'
                    ]
                ];
                $openid = Db::name('user')->where(['id' => $v['user_id']])->value('openid');
                if ($openid) {
                    sendWechatMsg('DzmIwZd8DUGLOjyC4Gx7ShlsDLu9MT1-uaHEUQ51kw4', $openid, $data, "pages/index/index");
                }
            }
            Db::name('msg')->insertAll($msg_data);
        }
    }

}
